package com.xyzim.firstcode.ui;

import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xyzim.firstcode.R;

import java.util.List;

public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.MyViewHolder> {
    private List<Fruit> mFruitList;

    public FruitAdapter(List<Fruit> fruitList){
        mFruitList = fruitList;
    }

    static class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tv;
        ImageView iv;
        View fruitItemView ;
        public MyViewHolder(View view){
            super(view);
            fruitItemView = view;
            tv = (TextView)view.findViewById(R.id.fruit_name);
            iv = (ImageView)view.findViewById(R.id.fruit_image);
        }
    }



    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.activity_fruit_item, parent, false);

        final MyViewHolder myViewHolder = new MyViewHolder(itemView);
        myViewHolder.fruitItemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = myViewHolder.getAdapterPosition();
                if(position<0){
                    Log.w("fruititemclick" ,"not clicked item");
                    return;
                }
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(),"you clicked view "+fruit.getName(),Toast.LENGTH_SHORT).show();
            }
        });

        myViewHolder.iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = myViewHolder.getAdapterPosition();
                if(position<0){
                    Log.w("fruititemclick" ,"not clicked image  item");
                    return;
                }
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(),"you clicked image "+fruit.getName(),Toast.LENGTH_SHORT).show();
            }
        });


        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Fruit fruite = mFruitList.get(position);
        holder.tv.setText(fruite.getName());
        holder.iv.setImageResource(fruite.getImageId());
    }

    @Override
    public int getItemCount() {
        return mFruitList.size();
    }
}

